#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""代码语法高亮组件"""

import re
import logging
from PyQt5.QtCore import Qt, QRegExp
from PyQt5.QtGui import (QColor, QFont, QSyntaxHighlighter, QTextCharFormat,
                        QTextDocument, QTextCursor)


class PythonSyntaxHighlighter(QSyntaxHighlighter):
    """Python语法高亮器"""
    
    def __init__(self, document=None):
        """初始化Python语法高亮器
        
        Args:
            document: QTextDocument对象
        """
        super().__init__(document)
        
        # 日志配置
        self.logger = logging.getLogger("PythonSyntaxHighlighter")
        
        # 高亮规则
        self.highlighting_rules = []
        
        # 高亮格式
        self.formats = {
            "keyword": self._create_format(QColor(165, 42, 42), bold=True),
            "string": self._create_format(QColor(188, 143, 143)),
            "comment": self._create_format(QColor(128, 128, 128), italic=True),
            "function": self._create_format(QColor(70, 130, 180)),
            "class": self._create_format(QColor(139, 69, 19), bold=True),
            "number": self._create_format(QColor(100, 149, 237)),
            "operator": self._create_format(QColor(0, 0, 0), bold=True),
            "bracket": self._create_format(QColor(0, 0, 128)),
            "builtin": self._create_format(QColor(0, 128, 128)),
            "decorator": self._create_format(QColor(218, 165, 32)),
            "self": self._create_format(QColor(128, 0, 128), bold=True),
        }
        
        # 初始化高亮规则
        self._init_highlighting_rules()
        
        # 多行注释和字符串的开始表达式
        self.multi_line_comment_start_expression = QRegExp(r'"""|\'\'\'')
        self.multi_line_string_start_expression = QRegExp(r'"""|\'\'\'')
        
        # 当前是否在多行注释或字符串中
        self.in_multiline_comment = False
        self.in_multiline_string = False
        
        # 运算符列表
        operators = [
            '=', '==', '!=', '<', '<=', '>', '>=', '+', '-', '*', '/', '//',
            '%', '**', '+=', '-=', '*=', '/=', '//=', '%=', '**=', '&',
            '|', '^', '~', '>>', '<<', '&=', '|=', '^=', '>>=', '<<='
        ]
        
        # 多行注释处理
        start_pattern = QRegExp(r'"""|\'\'\'')
        
        # 多行字符串处理
        start_pattern = QRegExp(r'"""|\'\'\'')
        
        for operator in operators:
            # 转义特殊字符
            escaped_operator = QRegExp.escape(operator)
            pattern = QRegExp(escaped_operator)
            rule = (pattern, self.formats["operator"])
            self.highlighting_rules.append(rule)
        
        # 添加括号高亮规则
        brackets = ['\\(', '\\)', '\\[', '\\]', '\\{', '\\}']
        
        for bracket in brackets:
            pattern = QRegExp(bracket)
            rule = (pattern, self.formats["bracket"])
            self.highlighting_rules.append(rule)
        
        # 添加函数名高亮规则
        function_pattern = QRegExp("\\b[A-Za-z0-9_]+(?=\\()")
        function_rule = (function_pattern, self.formats["function"])
        self.highlighting_rules.append(function_rule)
        
        # 添加类名高亮规则
        class_pattern = QRegExp("\\bclass\\s+(\\w+)\\b")
        class_pattern.setMinimal(True)
        class_rule = (class_pattern, 1, self.formats["class"])
        self.highlighting_rules.append(class_rule)
        
        # 添加装饰器高亮规则
        decorator_pattern = QRegExp("@\\w+\\b")
        decorator_rule = (decorator_pattern, self.formats["decorator"])
        self.highlighting_rules.append(decorator_rule)
    
    def highlightBlock(self, text):
        """高亮文本块
        
        Args:
            text: 文本块
        """
        try:
            # 应用单行高亮规则
            for rule in self.highlighting_rules:
                if len(rule) == 2:
                    pattern, format = rule
                    expression = QRegExp(pattern)
                    index = expression.indexIn(text)
                    while index >= 0:
                        length = expression.matchedLength()
                        self.setFormat(index, length, format)
                        index = expression.indexIn(text, index + length)
                elif len(rule) == 3:
                    pattern, nth, format = rule
                    expression = QRegExp(pattern)
                    index = expression.indexIn(text)
                    while index >= 0:
                        self.setFormat(expression.pos(nth), expression.cap(nth).length(), format)
                        index = expression.indexIn(text, index + 1)
            
            # 处理单行字符串
            # 单引号字符串
            string_pattern = QRegExp("'[^'\\\\]*(?:\\\\.[^'\\\\]*)*'")
            index = string_pattern.indexIn(text)
            while index >= 0:
                length = string_pattern.matchedLength()
                self.setFormat(index, length, self.formats["string"])
                index = string_pattern.indexIn(text, index + length)
            
            # 双引号字符串
            string_pattern = QRegExp('"[^"\\\\]*(?:\\\\.[^"\\\\]*)*"')
            index = string_pattern.indexIn(text)
            while index >= 0:
                length = string_pattern.matchedLength()
                self.setFormat(index, length, self.formats["string"])
                index = string_pattern.indexIn(text, index + length)
            
            # 处理单行注释
            comment_pattern = QRegExp("#.*$")
            index = comment_pattern.indexIn(text)
            if index >= 0:
                # 检查注释是否在字符串内部
                if not self._is_in_string(text, index):
                    self.setFormat(index, len(text) - index, self.formats["comment"])
            
            # 处理多行注释和字符串
            self._highlight_multiline(text)
        except Exception as e:
            self.logger.error(f"高亮文本块失败: {str(e)}")
    
    def _is_in_string(self, text, position):
        """检查位置是否在字符串内部
        
        Args:
            text: 文本
            position: 位置
            
        Returns:
            bool: 是否在字符串内部
        """
        # 检查单引号字符串
        string_pattern = QRegExp("'[^'\\\\]*(?:\\\\.[^'\\\\]*)*'")
        index = string_pattern.indexIn(text)
        while index >= 0:
            length = string_pattern.matchedLength()
            if index <= position < index + length:
                return True
            index = string_pattern.indexIn(text, index + length)
        
        # 检查双引号字符串
        string_pattern = QRegExp('"[^"\\\\]*(?:\\\\.[^"\\\\]*)*"')
        index = string_pattern.indexIn(text)
        while index >= 0:
            length = string_pattern.matchedLength()
            if index <= position < index + length:
                return True
            index = string_pattern.indexIn(text, index + length)
        
        return False
    
    def _highlight_multiline(self, text):
        """高亮多行注释和字符串
        
        Args:
            text: 文本
        """
        # 获取当前块的状态
        previous_block_state = self.previousBlockState()
        
        # 如果没有前一个块状态，设为0
        if previous_block_state == -1:
            previous_block_state = 0
        
        # 设置当前块的初始状态
        self.setCurrentBlockState(0)
        
        # 如果前一个块在多行注释中
        if previous_block_state == 1:
            self.in_multiline_comment = True
        # 如果前一个块在多行字符串中
        elif previous_block_state == 2:
            self.in_multiline_string = True
        else:
            self.in_multiline_comment = False
            self.in_multiline_string = False
        
        # 处理多行注释
        if self.in_multiline_comment:
            # 查找多行注释的结束
            end_pattern = QRegExp("""""|\'\'\'""")
            end_index = end_pattern.indexIn(text)
            
            if end_index >= 0:
                # 设置多行注释的格式
                self.setFormat(0, end_index + end_pattern.matchedLength(), self.formats["comment"])
                self.in_multiline_comment = False
                # 处理剩余文本
                remaining_text = text[end_index + end_pattern.matchedLength():]
                self.highlightBlock(remaining_text)
            else:
                # 没有找到结束，整个块都是多行注释
                self.setFormat(0, len(text), self.formats["comment"])
                self.in_multiline_comment = True
                self.setCurrentBlockState(1)
            
            return
        
        # 处理多行字符串
        if self.in_multiline_string:
            # 查找多行字符串的结束
            end_pattern = QRegExp("""""|\'\'\'""")
            end_index = end_pattern.indexIn(text)
            
            if end_index >= 0:
                # 设置多行字符串的格式
                self.setFormat(0, end_index + end_pattern.matchedLength(), self.formats["string"])
                self.in_multiline_string = False
                # 处理剩余文本
                remaining_text = text[end_index + end_pattern.matchedLength():]
                self.highlightBlock(remaining_text)
            else:
                # 没有找到结束，整个块都是多行字符串
                self.setFormat(0, len(text), self.formats["string"])
                self.in_multiline_string = True
                self.setCurrentBlockState(2)
            
            return
        
        # 查找多行注释的开始
        start_pattern = QRegExp(""""""|\'\'\'""")
        start_index = start_pattern.indexIn(text)
        
        if start_index >= 0:
            # 检查是否在字符串内部
            if not self._is_in_string(text, start_index):
                # 查找多行注释的结束
                end_index = start_pattern.indexIn(text, start_index + 3)
                
                if end_index >= 0:
                    # 单行多行注释
                    self.setFormat(start_index, end_index + 3 - start_index, self.formats["comment"])
                    # 处理剩余文本
                    remaining_text = text[end_index + 3:]
                    self.highlightBlock(remaining_text)
                else:
                    # 多行注释跨行
                    self.setFormat(start_index, len(text) - start_index, self.formats["comment"])
                    self.in_multiline_comment = True
                    self.setCurrentBlockState(1)
                
                return
        
        # 查找多行字符串的开始
        start_pattern = QRegExp(""""""|\'\'\'""")
        start_index = start_pattern.indexIn(text)
        
        if start_index >= 0:
            # 检查是否在注释内部
            if not self._is_in_comment(text, start_index):
                # 查找多行字符串的结束
                end_index = start_pattern.indexIn(text, start_index + 3)
                
                if end_index >= 0:
                    # 单行多行字符串
                    self.setFormat(start_index, end_index + 3 - start_index, self.formats["string"])
                    # 处理剩余文本
                    remaining_text = text[end_index + 3:]
                    self.highlightBlock(remaining_text)
                else:
                    # 多行字符串跨行
                    self.setFormat(start_index, len(text) - start_index, self.formats["string"])
                    self.in_multiline_string = True
                    self.setCurrentBlockState(2)
    
    def _is_in_comment(self, text, position):
        """检查位置是否在注释内部
        
        Args:
            text: 文本
            position: 位置
            
        Returns:
            bool: 是否在注释内部
        """
        # 检查单行注释
        comment_pattern = QRegExp("#.*$")
        index = comment_pattern.indexIn(text)
        while index >= 0:
            if index <= position:
                return True
            index = comment_pattern.indexIn(text, index + 1)
        
        # 检查多行注释
        comment_pattern = QRegExp(r'"""(?:.|\n)*?"""|\'\'\'(?:.|\n)*?\'\'\'')
        index = comment_pattern.indexIn(text)
        while index >= 0:
            length = comment_pattern.matchedLength()
            if index <= position < index + length:
                return True
            index = comment_pattern.indexIn(text, index + length)
        
        return False
    
    def set_theme(self, theme_name):
        """设置高亮主题
        
        Args:
            theme_name: 主题名称
        """
        try:
            # 主题定义
            themes = {
                "default": {
                    "keyword": (QColor(165, 42, 42), True),
                    "string": (QColor(188, 143, 143), False),
                    "comment": (QColor(128, 128, 128), True),
                    "function": (QColor(70, 130, 180), False),
                    "class": (QColor(139, 69, 19), True),
                    "number": (QColor(100, 149, 237), False),
                    "operator": (QColor(0, 0, 0), True),
                    "bracket": (QColor(0, 0, 128), False),
                    "builtin": (QColor(0, 128, 128), False),
                    "decorator": (QColor(218, 165, 32), False),
                    "self": (QColor(128, 0, 128), True),
                },
                "dark": {
                    "keyword": (QColor(255, 140, 0), True),
                    "string": (QColor(0, 255, 0), False),
                    "comment": (QColor(128, 128, 128), True),
                    "function": (QColor(173, 216, 230), False),
                    "class": (QColor(255, 192, 203), True),
                    "number": (QColor(255, 255, 0), False),
                    "operator": (QColor(255, 255, 255), True),
                    "bracket": (QColor(255, 215, 0), False),
                    "builtin": (QColor(0, 255, 255), False),
                    "decorator": (QColor(255, 99, 71), False),
                    "self": (QColor(221, 160, 221), True),
                },
                "monokai": {
                    "keyword": (QColor(249, 38, 114), True),
                    "string": (QColor(230, 219, 116), False),
                    "comment": (QColor(117, 113, 94), True),
                    "function": (QColor(166, 226, 46), False),
                    "class": (QColor(102, 217, 239), True),
                    "number": (QColor(174, 129, 255), False),
                    "operator": (QColor(255, 255, 255), True),
                    "bracket": (QColor(255, 255, 255), False),
                    "builtin": (QColor(102, 217, 239), False),
                    "decorator": (QColor(253, 151, 31), False),
                    "self": (QColor(255, 174, 201), True),
                }
            }
            
            # 检查主题是否存在
            if theme_name not in themes:
                self.logger.warning(f"未知的主题: {theme_name}")
                return
            
            # 更新格式
            theme = themes[theme_name]
            for name, (color, bold) in theme.items():
                if name in self.formats:
                    self.formats[name] = self._create_format(color, bold)
            
            # 重新高亮文档
            if self.document():
                self.rehighlight()
            
            self.logger.info(f"已设置高亮主题: {theme_name}")
        except Exception as e:
            self.logger.error(f"设置高亮主题失败: {str(e)}")
    
    def set_font(self, font_family, font_size):
        """设置字体
        
        Args:
            font_family: 字体名称
            font_size: 字体大小
        """
        try:
            # 创建字体
            font = QFont(font_family, font_size)
            
            # 更新所有格式的字体
            for name in self.formats:
                self.formats[name].setFont(font)
            
            # 重新高亮文档
            if self.document():
                self.rehighlight()
            
            self.logger.info(f"已设置高亮字体: {font_family}, 大小: {font_size}")
        except Exception as e:
            self.logger.error(f"设置字体失败: {str(e)}")


class XmlSyntaxHighlighter(QSyntaxHighlighter):
    """XML语法高亮器"""
    
    def __init__(self, document=None):
        """初始化XML语法高亮器
        
        Args:
            document: QTextDocument对象
        """
        super().__init__(document)
        
        # 日志配置
        self.logger = logging.getLogger("XmlSyntaxHighlighter")
        
        # 高亮规则
        self.highlighting_rules = []
        
        # 高亮格式
        self.formats = {
            "tag": self._create_format(QColor(165, 42, 42), bold=True),
            "attribute": self._create_format(QColor(139, 69, 19)),
            "value": self._create_format(QColor(188, 143, 143)),
            "comment": self._create_format(QColor(128, 128, 128), italic=True),
            "doctype": self._create_format(QColor(0, 128, 128), italic=True),
        }
        
        # 初始化高亮规则
        self._init_highlighting_rules()
        
        # 多行注释的开始和结束表达式
        self.comment_start_expression = QRegExp("<!--")
        self.comment_end_expression = QRegExp("-->")
        
        # 当前是否在多行注释中
        self.in_comment = False
    
    def _create_format(self, color, bold=False, italic=False, underline=False):
        """创建文本格式
        
        Args:
            color: 颜色
            bold: 是否粗体
            italic: 是否斜体
            underline: 是否下划线
            
        Returns:
            QTextCharFormat: 文本格式
        """
        text_format = QTextCharFormat()
        text_format.setForeground(color)
        
        if bold:
            text_format.setFontWeight(QFont.Bold)
        
        if italic:
            text_format.setFontItalic(True)
        
        if underline:
            text_format.setFontUnderline(True)
        
        return text_format
    
    def _init_highlighting_rules(self):
        """初始化高亮规则"""
        # 添加标签高亮规则
        tag_pattern = QRegExp("<\\/?\\w+")
        tag_rule = (tag_pattern, self.formats["tag"])
        self.highlighting_rules.append(tag_rule)
        
        # 添加属性高亮规则
        attribute_pattern = QRegExp("\\s\\w+=")
        attribute_rule = (attribute_pattern, self.formats["attribute"])
        self.highlighting_rules.append(attribute_rule)
        
        # 添加属性值高亮规则
        # 单引号
        value_pattern = QRegExp("'[^']*'")
        value_rule = (value_pattern, self.formats["value"])
        self.highlighting_rules.append(value_rule)
        
        # 双引号
        value_pattern = QRegExp('"[^"]*"')
        value_rule = (value_pattern, self.formats["value"])
        self.highlighting_rules.append(value_rule)
        
        # 添加DOCTYPE高亮规则
        doctype_pattern = QRegExp("<!DOCTYPE[^>]*>")
        doctype_rule = (doctype_pattern, self.formats["doctype"])
        self.highlighting_rules.append(doctype_rule)
    
    def highlightBlock(self, text):
        """高亮文本块
        
        Args:
            text: 文本块
        """
        try:
            # 如果在多行注释中，查找注释的结束
            if self.in_comment:
                self._highlight_multiline_comment(text)
                return
            
            # 应用单行高亮规则
            for pattern, format in self.highlighting_rules:
                expression = QRegExp(pattern)
                index = expression.indexIn(text)
                while index >= 0:
                    length = expression.matchedLength()
                    self.setFormat(index, length, format)
                    index = expression.indexIn(text, index + length)
            
            # 检查多行注释的开始
            comment_start_index = self.comment_start_expression.indexIn(text)
            if comment_start_index >= 0:
                # 设置多行注释的格式
                self.setFormat(comment_start_index, len(text) - comment_start_index, self.formats["comment"])
                self.in_comment = True
                self.setCurrentBlockState(1)
        except Exception as e:
            self.logger.error(f"高亮文本块失败: {str(e)}")
    
    def _highlight_multiline_comment(self, text):
        """高亮多行注释
        
        Args:
            text: 文本
        """
        # 查找注释的结束
        comment_end_index = self.comment_end_expression.indexIn(text)
        
        if comment_end_index >= 0:
            # 注释在当前块结束
            self.setFormat(0, comment_end_index + self.comment_end_expression.matchedLength(), self.formats["comment"])
            self.in_comment = False
            self.setCurrentBlockState(0)
            
            # 处理剩余文本
            remaining_text = text[comment_end_index + self.comment_end_expression.matchedLength():]
            self.highlightBlock(remaining_text)
        else:
            # 注释跨行
            self.setFormat(0, len(text), self.formats["comment"])
            self.in_comment = True
            self.setCurrentBlockState(1)
    
    def set_theme(self, theme_name):
        """设置高亮主题
        
        Args:
            theme_name: 主题名称
        """
        try:
            # 主题定义
            themes = {
                "default": {
                    "tag": (QColor(165, 42, 42), True),
                    "attribute": (QColor(139, 69, 19), False),
                    "value": (QColor(188, 143, 143), False),
                    "comment": (QColor(128, 128, 128), True),
                    "doctype": (QColor(0, 128, 128), True),
                },
                "dark": {
                    "tag": (QColor(255, 140, 0), True),
                    "attribute": (QColor(255, 192, 203), False),
                    "value": (QColor(0, 255, 0), False),
                    "comment": (QColor(128, 128, 128), True),
                    "doctype": (QColor(0, 255, 255), True),
                }
            }
            
            # 检查主题是否存在
            if theme_name not in themes:
                self.logger.warning(f"未知的主题: {theme_name}")
                return
            
            # 更新格式
            theme = themes[theme_name]
            for name, (color, bold) in theme.items():
                if name in self.formats:
                    self.formats[name] = self._create_format(color, bold)
            
            # 重新高亮文档
            if self.document():
                self.rehighlight()
            
            self.logger.info(f"已设置高亮主题: {theme_name}")
        except Exception as e:
            self.logger.error(f"设置高亮主题失败: {str(e)}")


class JavaScriptSyntaxHighlighter(QSyntaxHighlighter):
    """JavaScript语法高亮器"""
    
    def __init__(self, document=None):
        """初始化JavaScript语法高亮器
        
        Args:
            document: QTextDocument对象
        """
        super().__init__(document)
        
        # 日志配置
        self.logger = logging.getLogger("JavaScriptSyntaxHighlighter")
        
        # 高亮规则
        self.highlighting_rules = []
        
        # 高亮格式
        self.formats = {
            "keyword": self._create_format(QColor(165, 42, 42), bold=True),
            "string": self._create_format(QColor(188, 143, 143)),
            "comment": self._create_format(QColor(128, 128, 128), italic=True),
            "function": self._create_format(QColor(70, 130, 180)),
            "number": self._create_format(QColor(100, 149, 237)),
            "operator": self._create_format(QColor(0, 0, 0), bold=True),
            "bracket": self._create_format(QColor(0, 0, 128)),
            "builtin": self._create_format(QColor(0, 128, 128)),
            "regex": self._create_format(QColor(255, 69, 0)),
        }
        
        # 初始化高亮规则
        self._init_highlighting_rules()
        
        # 多行注释的开始和结束表达式
        self.comment_start_expression = QRegExp("/\\*")
        self.comment_end_expression = QRegExp("\\*/")
        
        # 当前是否在多行注释中
        self.in_comment = False
    
    def _create_format(self, color, bold=False, italic=False, underline=False):
        """创建文本格式
        
        Args:
            color: 颜色
            bold: 是否粗体
            italic: 是否斜体
            underline: 是否下划线
            
        Returns:
            QTextCharFormat: 文本格式
        """
        text_format = QTextCharFormat()
        text_format.setForeground(color)
        
        if bold:
            text_format.setFontWeight(QFont.Bold)
        
        if italic:
            text_format.setFontItalic(True)
        
        if underline:
            text_format.setFontUnderline(True)
        
        return text_format
    
    def _init_highlighting_rules(self):
        """初始化高亮规则"""
        # JavaScript关键字
        keywords = [
            'break', 'case', 'catch', 'class', 'const', 'continue', 'debugger',
            'default', 'delete', 'do', 'else', 'export', 'extends', 'finally',
            'for', 'function', 'if', 'import', 'in', 'instanceof', 'new',
            'return', 'super', 'switch', 'this', 'throw', 'try', 'typeof',
            'var', 'void', 'while', 'with', 'yield', 'let', 'static',
            'enum', 'await', 'implements', 'package', 'protected', 'interface',
            'private', 'public'
        ]
        
        # 添加关键字高亮规则
        for keyword in keywords:
            pattern = QRegExp(f"\\b{keyword}\\b")
            rule = (pattern, self.formats["keyword"])
            self.highlighting_rules.append(rule)
        
        # 添加内置函数高亮规则
        builtins = [
            'Array', 'Boolean', 'Date', 'Error', 'Function', 'Math', 'Number',
            'Object', 'RegExp', 'String', 'Symbol', 'Promise', 'Proxy', 'Map',
            'Set', 'WeakMap', 'WeakSet', 'Int8Array', 'Uint8Array', 'Int16Array',
            'Uint16Array', 'Int32Array', 'Uint32Array', 'Float32Array', 'Float64Array',
            'isFinite', 'isNaN', 'parseFloat', 'parseInt', 'decodeURI', 'decodeURIComponent',
            'encodeURI', 'encodeURIComponent', 'escape', 'unescape', 'eval',
            'globalThis', 'Infinity', 'NaN', 'undefined'
        ]
        
        for builtin in builtins:
            pattern = QRegExp(f"\\b{builtin}\\b")
            rule = (pattern, self.formats["builtin"])
            self.highlighting_rules.append(rule)
        
        # 添加数字高亮规则
        number_pattern = QRegExp("\\b[0-9]+(\\.[0-9]+)?([eE][+-]?[0-9]+)?\\b")
        number_rule = (number_pattern, self.formats["number"])
        self.highlighting_rules.append(number_rule)
        
        # 添加运算符高亮规则
        operators = [
            '=', '==', '!=', '===', '!==', '<', '<=', '>', '>=', '\+', '-',
            '\*', '/', '%', '\*\*', '\+=', '-=', '\*=', '/=', '%=', '\*\*=',
            '&', '|', '^', '~', '>>', '<<', '>>>', '&=', '|=', '^=', '>>=',
            '<<=', '>>>=', '!', '&&', '||', '?', ':', '++', '--'
        ]
        
        for operator in operators:
            # 转义特殊字符
            escaped_operator = QRegExp.escape(operator)
            pattern = QRegExp(escaped_operator)
            rule = (pattern, self.formats["operator"])
            self.highlighting_rules.append(rule)
        
        # 添加括号高亮规则
        brackets = ['\\(', '\\)', '\\[', '\\]', '\\{', '\\}']
        
        for bracket in brackets:
            pattern = QRegExp(bracket)
            rule = (pattern, self.formats["bracket"])
            self.highlighting_rules.append(rule)
        
        # 添加函数名高亮规则
        function_pattern = QRegExp("\\b[A-Za-z0-9_]+(?=\\()")
        function_rule = (function_pattern, self.formats["function"])
        self.highlighting_rules.append(function_rule)
        
        # 添加字符串高亮规则
        # 单引号字符串
        string_pattern = QRegExp("'[^'\\\\]*(?:\\\\.[^'\\\\]*)*'")
        string_rule = (string_pattern, self.formats["string"])
        self.highlighting_rules.append(string_rule)
        
        # 双引号字符串
        string_pattern = QRegExp('"[^"\\\\]*(?:\\\\.[^"\\\\]*)*"')
        string_rule = (string_pattern, self.formats["string"])
        self.highlighting_rules.append(string_rule)
        
        # 模板字符串 (ES6)
        string_pattern = QRegExp('`[^`\\\\]*(?:\\\\.[^`\\\\]*)*`')
        string_rule = (string_pattern, self.formats["string"])
        self.highlighting_rules.append(string_rule)
        
        # 添加正则表达式高亮规则
        # 注意：这个规则可能会有误判，因为正则表达式的语法比较复杂
        regex_pattern = QRegExp("/[^/\\\\]*(?:\\\\.[^/\\\\]*)*/[gimuy]*")
        regex_rule = (regex_pattern, self.formats["regex"])
        self.highlighting_rules.append(regex_rule)
    
    def highlightBlock(self, text):
        """高亮文本块
        
        Args:
            text: 文本块
        """
        try:
            # 如果在多行注释中，查找注释的结束
            if self.in_comment:
                self._highlight_multiline_comment(text)
                return
            
            # 应用单行高亮规则
            for pattern, format in self.highlighting_rules:
                expression = QRegExp(pattern)
                index = expression.indexIn(text)
                while index >= 0:
                    # 检查是否在字符串内部
                    if not self._is_in_string(text, index):
                        length = expression.matchedLength()
                        self.setFormat(index, length, format)
                    index = expression.indexIn(text, index + 1)
            
            # 处理单行注释
            comment_pattern = QRegExp("//.*$")
            index = comment_pattern.indexIn(text)
            if index >= 0:
                # 检查注释是否在字符串内部
                if not self._is_in_string(text, index):
                    self.setFormat(index, len(text) - index, self.formats["comment"])
            
            # 检查多行注释的开始
            comment_start_index = self.comment_start_expression.indexIn(text)
            if comment_start_index >= 0:
                # 检查是否在字符串内部
                if not self._is_in_string(text, comment_start_index):
                    # 设置多行注释的格式
                    self.setFormat(comment_start_index, len(text) - comment_start_index, self.formats["comment"])
                    self.in_comment = True
                    self.setCurrentBlockState(1)
        except Exception as e:
            self.logger.error(f"高亮文本块失败: {str(e)}")
    
    def _is_in_string(self, text, position):
        """检查位置是否在字符串内部
        
        Args:
            text: 文本
            position: 位置
            
        Returns:
            bool: 是否在字符串内部
        """
        # 检查单引号字符串
        string_pattern = QRegExp("'[^'\\\\]*(?:\\\\.[^'\\\\]*)*'")
        index = string_pattern.indexIn(text)
        while index >= 0:
            length = string_pattern.matchedLength()
            if index <= position < index + length:
                return True
            index = string_pattern.indexIn(text, index + length)
        
        # 检查双引号字符串
        string_pattern = QRegExp('"[^"\\\\]*(?:\\\\.[^"\\\\]*)*"')
        index = string_pattern.indexIn(text)
        while index >= 0:
            length = string_pattern.matchedLength()
            if index <= position < index + length:
                return True
            index = string_pattern.indexIn(text, index + length)
        
        # 检查模板字符串
        string_pattern = QRegExp('`[^`\\\\]*(?:\\\\.[^`\\\\]*)*`')
        index = string_pattern.indexIn(text)
        while index >= 0:
            length = string_pattern.matchedLength()
            if index <= position < index + length:
                return True
            index = string_pattern.indexIn(text, index + length)
        
        return False
    
    def _highlight_multiline_comment(self, text):
        """高亮多行注释
        
        Args:
            text: 文本
        """
        # 查找注释的结束
        comment_end_index = self.comment_end_expression.indexIn(text)
        
        if comment_end_index >= 0:
            # 注释在当前块结束
            self.setFormat(0, comment_end_index + self.comment_end_expression.matchedLength(), self.formats["comment"])
            self.in_comment = False
            self.setCurrentBlockState(0)
            
            # 处理剩余文本
            remaining_text = text[comment_end_index + self.comment_end_expression.matchedLength():]
            self.highlightBlock(remaining_text)
        else:
            # 注释跨行
            self.setFormat(0, len(text), self.formats["comment"])
            self.in_comment = True
            self.setCurrentBlockState(1)
    
    def set_theme(self, theme_name):
        """设置高亮主题
        
        Args:
            theme_name: 主题名称
        """
        try:
            # 主题定义
            themes = {
                "default": {
                    "keyword": (QColor(165, 42, 42), True),
                    "string": (QColor(188, 143, 143), False),
                    "comment": (QColor(128, 128, 128), True),
                    "function": (QColor(70, 130, 180), False),
                    "number": (QColor(100, 149, 237), False),
                    "operator": (QColor(0, 0, 0), True),
                    "bracket": (QColor(0, 0, 128), False),
                    "builtin": (QColor(0, 128, 128), False),
                    "regex": (QColor(255, 69, 0), False),
                },
                "dark": {
                    "keyword": (QColor(255, 140, 0), True),
                    "string": (QColor(0, 255, 0), False),
                    "comment": (QColor(128, 128, 128), True),
                    "function": (QColor(173, 216, 230), False),
                    "number": (QColor(255, 255, 0), False),
                    "operator": (QColor(255, 255, 255), True),
                    "bracket": (QColor(255, 215, 0), False),
                    "builtin": (QColor(0, 255, 255), False),
                    "regex": (QColor(255, 99, 71), False),
                }
            }
            
            # 检查主题是否存在
            if theme_name not in themes:
                self.logger.warning(f"未知的主题: {theme_name}")
                return
            
            # 更新格式
            theme = themes[theme_name]
            for name, (color, bold) in theme.items():
                if name in self.formats:
                    self.formats[name] = self._create_format(color, bold)
            
            # 重新高亮文档
            if self.document():
                self.rehighlight()
            
            self.logger.info(f"已设置高亮主题: {theme_name}")
        except Exception as e:
            self.logger.error(f"设置高亮主题失败: {str(e)}")